package com.shop.handler;

import cn.hutool.json.JSONUtil;
import com.shop.common.SetMeta;
import com.shop.entity.Manager;
import com.shop.service.ManagerService;
import com.shop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    ManagerService managerService;



    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();


        // 生成jwt，并放置到请求头中
        String jwt = jwtUtil.generateToken(authentication.getName());
        httpServletResponse.setHeader(jwtUtil.getHeader(), jwt);

        // 生成用户数据
        String username = authentication.getName();
        Manager manager = managerService.getUsername(username);
        manager.setToken(jwt);
        manager.setPassword(null);
        manager.setType(null);

        SetMeta setMeta = new SetMeta();
        setMeta.setSuccess(manager,"登录成功");
        outputStream.write(JSONUtil.toJsonStr(setMeta).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
